// index.ts - 排球小程序首页
import { checkHealth, testApiConnection, isApiHealthy, getServerInfo, getHealthTest } from '../../api/health'

Component({
  data: {
    // 视角切换状态：true为新人视角，false为队员视角
// 视角切换状态：true为新人视角，false为队员视角
    isNewMember: true,

    // 轮播图数据
    carouselItems: [
      {
        id: 1,
        type: 'image',
        bgColor: '#2E8B57', // 海绿背景
        title: '队员训练集锦',
        description: '日常训练精彩片段回顾',
        icon: '▶️',
        category: 'skill'
      },
      {
        id: 2,
        type: 'image',
        bgColor: '#4682B4', // 钢蓝背景
        title: '下周赛事预告',
        description: '城市联赛半决赛即将开始',
        icon: '🗓️',
        category: 'macth'
      }
      // 可以添加更多轮播图项
    ],
    // 当前轮播图索引
    currentCarouselIndex: 0,
    // 当前指示器颜色
    currentIndicatorColor: '#FFFFFF',
    
    // 队员位置列表
    positions: ['全部', '主攻', '二传', '副攻', '接应', '自由人'],
    activePosition: 'all',
    
    // 队员数据
    players: [
      { id: 1, name: '张明', number: 1, position: 'spiker', avatar: 'https://picsum.photos/100/100?random=101' },
      { id: 2, name: '李华', number: 2, position: 'setter', avatar: 'https://picsum.photos/100/100?random=102' },
      { id: 3, name: '王强', number: 3, position: 'middle', avatar: 'https://picsum.photos/100/100?random=103' },
      { id: 4, name: '赵刚', number: 4, position: 'opposite', avatar: 'https://picsum.photos/100/100?random=104' },
      { id: 5, name: '陈杰', number: 5, position: 'libero', avatar: 'https://picsum.photos/100/100?random=105' },
      { id: 6, name: '刘洋', number: 6, position: 'spiker', avatar: 'https://picsum.photos/100/100?random=106' },
    ],
    
    // 增强的赛事数据 - 包含更详细的信息
    matches: [
      {
        id: 1,
        title: '春季联赛半决赛',
        date: '2024-05-15',
        time: '19:30',
        location: '市体育馆主馆',
        status: 'upcoming',
        teamARoster: [1, 2, 3, 4, 5, 6],
      },
      {
        id: 2,
        title: '友谊赛',
        date: '2024-05-10',
        time: '15:00',
        location: '学校体育场2号场',
        status: 'completed',
        teamARoster: [1, 3, 4, 6, 8, 9],
        result: '飞翔队 3:1 星光队',
      }
    ],
    
    // 当前赛事类型筛选
    activeMatchStatus: 'upcoming',
    
    // 通知数据
    notifications: [
      {
        id: 1,
        title: '训练时间变更通知',
        description: '原定于周三的训练改为周四下午6点',
        time: '今天 10:30',
        unread: true
      },
      {
        id: 2,
        title: '半决赛名单公布',
        description: '请查看最新公布的半决赛参赛名单',
        time: '昨天 18:45',
        unread: true
      },
      {
        id: 3,
        title: '新队员招募结束',
        description: '本次新队员招募工作已顺利结束',
        time: '2024-05-01',
        unread: false
      }
    ],
    
    // 训练安排数据
    trainingSessions: [
      {
        id: 1,
        day: '11',
        weekday: '周三',
        time: '18:30-20:30',
        topic: '发球与接发球训练',
        location: '城东体育馆',
        equipment: '排球、运动服、护腕'
      },
      {
        id: 2,
        day: '13',
        weekday: '周五',
        time: '15:00-17:00',
        topic: '战术配合演练',
        location: '城东体育馆',
        equipment: '排球、运动服、护膝'
      }
    ],
    
    // 新增筛选后的数据存储
    filteredPlayers: [],
    filteredMatches: []
  },
  
  lifetimes: {
    attached() {
      console.log('🏐 排球小程序首页加载')
      this.performHealthCheck()
      this.updateFilteredData()
    }
  },
  
  methods: {
    // 筛选队员列表
    getFilteredPlayers() {
      if (this.data.activePosition === 'all') {
        return this.data.players;
      }
      return this.data.players.filter(player => player.position === this.data.activePosition);
    },
    
    // 筛选赛事列表并补充队员信息
    getFilteredMatches() {
      return this.data.matches
        .filter(match => match.status === this.data.activeMatchStatus)
        .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime())
        .map(match => {
          const members = match.teamARoster.map(id => {
            const player = this.data.players.find(p => p.id === id);
            return player ? player.name : '';
          }).filter(Boolean);
          return {
            ...match,
            members
          };
        });
    },
    
    // 更新筛选数据
    updateFilteredData() {
      this.setData({
        filteredPlayers: this.getFilteredPlayers() as any,
        filteredMatches: this.getFilteredMatches() as any
      });
    },

    // 助手函数：获取位置中文名
    getPositionText(position: string) {
      const positionMap = {
        spiker: '主攻',
        setter: '二传',
        middle: '副攻',
        opposite: '接应',
        libero: '自由人'
      };
      return (positionMap as Record<string, string>)[position] || '';
    },

    // 助手函数：获取位置对应颜色
    getPositionColor(position: string) {
      const colorMap = {
        spiker: '#FF6347',   // 番茄红
        setter: '#4682B4',   // 钢青色
        middle: '#32CD32',   // 酸橙绿
        opposite: '#FFA500', // 橙色
        libero: '#DAA520'    // 金色
      };
      return (colorMap as Record<string, string>)[position] || '#999';
    },

    // 执行健康检查
    async performHealthCheck() {
      console.log('=== 🔍 API健康检查开始 ===');
      try {
        const healthResponse = await checkHealth();
        console.log('✅ 基础健康检查结果:', healthResponse);
        const connectionTest = await testApiConnection();
        console.log('🔗 连接测试结果:', connectionTest);
        const isHealthy = await isApiHealthy();
        console.log('⚡ 快速检查结果 - API是否健康:', isHealthy);
        const serverInfo = await getServerInfo();
        console.log('🖥️ 服务器信息:', serverInfo);
        const healthTest = await getHealthTest();
        console.log('🔍 健康测试结果:', healthTest);
        
        if (isHealthy) {
          console.log('🎉 所有健康检查通过！');
        }
      } catch (error: any) {
        console.error('❌ 健康检查过程中发生错误:', error);
      }
    },
    
    // 切换新人/队员视角
    toggleView() {
      this.setData({
        isNewMember: !this.data.isNewMember
      });
    },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    // 初始化时为每个轮播项添加按钮颜色
    this.processCarouselColors();
  },

  /**
   * 处理轮播图颜色，为每个项添加相反的按钮色
   */
  processCarouselColors() {
    const processedItems = this.data.carouselItems.map(item => ({
      ...item,
      btnColor: this.getReverseColor(item.bgColor)
    }));
    
    this.setData({
      carouselItems: processedItems
    });
  },

  /**
   * 根据背景色获取相反的按钮颜色 - 自然和谐方案
   * @param backgroundColor 背景色值
   * @returns 相反的按钮颜色
   */
  getReverseColor(backgroundColor: string): string {
    // 自然和谐色彩搭配
    if (backgroundColor === '#2E8B57') {
      return '#F4A460'; // 海绿配沙棕
    } else if (backgroundColor === '#4682B4') {
      return '#DDA0DD'; // 钢蓝配梅紫
    }
    // 默认返回沙棕色
    return '#F4A460';
  },

  /**
   * 轮播图切换事件 - 动态调整指示器颜色
   */
  onCarouselChange(e: any) {
    const currentIndex = e.detail.current;
    const currentItem = this.data.carouselItems[currentIndex];
    
    // 根据背景色设置指示器颜色 - 自然和谐方案
    let indicatorColor = '#FFFFFF';
    if (currentItem.bgColor === '#2E8B57') {
      indicatorColor = '#F4A460'; // 海绿背景用沙棕指示器
    } else if (currentItem.bgColor === '#4682B4') {
      indicatorColor = '#DDA0DD'; // 钢蓝背景用梅紫指示器
    }
    
    this.setData({
      currentCarouselIndex: currentIndex,
      currentIndicatorColor: indicatorColor
    });
  },
    
    // 轮播图点击事件
    onCarouselItemTap(e: any) {
      const item = e.currentTarget.dataset.item;
      console.log('点击了轮播图项目:', item);
      
      // 假设使用item的某个属性（如category）来区分跳转不同的图文页面
      // 你可以根据实际需求修改判断条件
      if (item.category === 'skill') {
        wx.navigateTo({
              url: `/subpackage_volleyball/graphic_details/graphic_details?id=${item.id}`
        });
      } else {
        wx.navigateTo({
              url: `/subpackage_volleyball/image_details/image_details?id=${item.id}`
        });
      }
    },

    
    // 位置筛选事件
    handlePositionChange(e: any) {
      this.setData({
        activePosition: e.currentTarget.dataset.position
      }, () => {
        this.updateFilteredData();
      });
    },

    // 赛事状态筛选
    setActiveMatchStatus(e: any) {
      this.setData({
        activeMatchStatus: e.currentTarget.dataset.status
      }, () => {
        this.updateFilteredData();
      });
    },
    
    // 下拉刷新
    onPullDownRefresh() {
      console.log('下拉刷新数据');
      setTimeout(() => {
        this.updateFilteredData();
        wx.stopPullDownRefresh();
      }, 1000);
    },
    
    // 页面跳转函数
    navigateToTeamAbout() {
      wx.navigateTo({
        url: '/subpackage_volleyball/team_about/team_about'
      });
    },
    
    navigateToPlayersList() {
      wx.navigateTo({
        url: '/subpackage_volleyball/players_list/players_list'
      });
    },
    
    navigateToMatches() {
      wx.navigateTo({
        url: '/subpackage_volleyball/matches/matches'
      });
    },
    
    navigateToTraining() {
      wx.navigateTo({
        url: '/subpackage_volleyball/training/training'
      });
    },
    
    navigateToNotificationDetails(e: any) {
      const id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: `/subpackage_volleyball/notifications_details/notifications_details?id=${id}`
      });
    },
    
    navigateToKnowledge(e?: any) {
      // 如果有事件参数，获取知识类型
      const knowledgeType = e?.currentTarget?.dataset?.type;
      
      if (knowledgeType === 'rules') {
        wx.navigateTo({
          url: '/subpackage_volleyball/knowledge_rules/knowledge_rules'
        });
      } else if (knowledgeType === 'skills') {
        wx.navigateTo({
          url: '/subpackage_volleyball/knowledge_skills/knowledge_skills'
        });
      } else if (knowledgeType === 'tactics') {
        wx.navigateTo({
          url: '/subpackage_volleyball/knowledge_tactics/knowledge_tactics'
        });
      } else {
        // 默认跳转到通用知识页面
        wx.navigateTo({
          url: '/subpackage_volleyball/knowledge/knowledge'
        });
      }
    },
    
    navigateToNotifications() {
      wx.navigateTo({
        url: '/subpackage_volleyball/notifications_details/notifications_details'
      });
    },
    
    // 下载二维码图片
    downloadQRCode() {
      wx.showLoading({
        title: '正在保存...',
      });
      
      // 获取本地图片路径并保存到相册
      const localImagePath = '/static/images/qr.png';
      
      wx.saveImageToPhotosAlbum({
        filePath: localImagePath,
        success: () => {
          wx.hideLoading();
          wx.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 2000
          });
        },
        fail: (error: any) => {
          wx.hideLoading();
          console.error('保存图片失败:', error);
          if (error.errMsg.includes('auth') || error.errMsg.includes('deny')) {
            // 用户拒绝授权，引导用户开启权限
            wx.showModal({
              title: '提示',
              content: '需要您授权保存图片到相册，请在设置中开启相册权限',
              confirmText: '去设置',
              cancelText: '取消',
              success: (res) => {
                if (res.confirm) {
                  wx.openSetting({
                    success: (settingRes) => {
                      if (settingRes.authSetting['scope.writePhotosAlbum']) {
                        wx.showToast({
                          title: '授权成功',
                          icon: 'success'
                        });
                      }
                    }
                  });
                }
              }
            });
          } else if (error.errMsg.includes('fail')) {
            // 图片路径可能有问题，尝试使用绝对路径
            const absolutePath = `${wx.env.USER_DATA_PATH}/qr.png`;
            // 或者提示用户长按保存
            wx.showModal({
              title: '保存失败',
              content: '自动保存失败，您可以长按二维码图片手动保存',
              showCancel: false,
              confirmText: '知道了'
            });
          } else {
            wx.showToast({
              title: '保存失败',
              icon: 'error',
              duration: 2000
            });
          }
        }
      });
    },
        // 确认参加训练按钮点击事件
        confirmAttendance(e: any) {
          const id = e.currentTarget.dataset.id; // 可选，获取训练ID
          console.log(`确认参加了 ID 为 ${id} 的训练`);
    
          wx.showToast({
            title: '参加成功',
            icon: 'success',
            duration: 2000
          });
    
          // TODO: 在这里可以添加实际的业务逻辑，例如：
          // 1. 调用后端 API 记录用户的参加状态
          // 2. 更新页面的数据，例如改变按钮的文字或样式
          // 3. 可以在这里更新 trainingSessions 数组，把该项的参加状态设置为已参加
        },
  }
});